// module.exports = function(mainApp) {
/*
 * 基于angular.js的控制器，负责与view进行交互。 
 */
var mainApp = angular.module("mainApp");
mainApp.controller('RootController', ["$scope", "$rootScope", "DPUtil", '$location',
    function($scope, $rootScope, DPUtil, $location) {

        $scope.pathUrl = function(url) {
            $location.path(url);
        }
    }
]);
mainApp.controller('loginAppCtrl', ["$scope", "DPUtil", "$ionicSideMenuDelegate", "$rootScope", "$state", "appService",
    function($scope, DPUtil, $ionicSideMenuDelegate, $rootScope, $state, appService) {
        $scope.user = {};
        $scope.login = function() {
            if (!$scope.user.username) {
                $scope.tip = "请输入账号";
                return false;
            }
            if (!$scope.user.password) {
                $scope.tip = "请输入密码";
                return false;
            }
            appService.login($scope.user).then(function(data) {
                if (data.success) {
                    $state.go("customerList");
                } else {
                    $scope.tip = data.failureMessage;
                }
            });
        }
    }
]);
mainApp.controller('customerListCtrl', ["$scope", "DPUtil", "$ionicSideMenuDelegate", "$rootScope", "$state", "appService", "$ionicPopup",
    function($scope, DPUtil, $ionicSideMenuDelegate, $rootScope, $state, appService, $ionicPopup) {
        $scope.conditions = {
            page: 0,
            rows: 10
        };
        $scope.isScroll = true;
        $scope.items = [];
        var obj = { name: "tao" };
        $scope.loadMore = function(type) {
            if (type) {
                $scope.conditions.page = 1;
            } else {
                $scope.conditions.page++;
            }
            appService.list($scope.conditions).then(function(data) {
                console.log($scope.items);
                if (type) {
                    $scope.items = data.content;
                } else {
                    $scope.items = $scope.items.concat(data.content);
                }
                $scope.total = data.recordCount;
                if ($scope.items.length >= $scope.total) {
                    $scope.isScroll = false;
                };
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });

            // $scope.isScroll = false;
            // $rootScope.panels.isLoadingToastShow = true;

        };
        $scope.$on('stateChangeSuccess', function() {
            $scope.loadMore();
        });
        // $scope.loadMore();
        $scope.toggleRightSideMenu = function() {
            $ionicSideMenuDelegate.toggleRight();
        };
        $scope.goUrl = function(id) {
            $state.go("customerDetail", { id: id });
        }
        $scope.logout = function() {
            var confirmPopup = $ionicPopup.confirm({
                title: '提示',
                template: '确定退出登录?',
                cancelText: '取消',
                okText: "确定"
            });
            confirmPopup.then(function(res) {
                if (res) {
                    appService.logout().then(function(data) {
                        if (data.success) {
                            $state.go("loginApp");
                        }
                    });
                } else {
                    // console.log('You are not sure');
                }
            });

        }
    }
]);
mainApp.controller('customerDetailCtrl', ["$scope", "DPUtil", "$stateParams", "appService", "$state",
    function($scope, DPUtil, $stateParams, appService, $state) {
        $scope.id = $stateParams.id;
        $scope.g_clientType = [];
        $scope.g_document = [];
        $scope.g_condition = [];
        $scope.g_preResult = [];
        $scope.g_finallyResult = [];
        $scope.g_periods = [];
        $scope.myItem = [];
        // 获取大小项目
        $scope.getMyItem = function() {
            if ($scope.myItem.length > 0) {
                return false;
            }
            appService.item({
                page: 1,
                rows: 9000
            }).then(function(data) {
                $scope.myItem = data.content;
                for (var i = 0; i < $scope.myItem.length; i++) {
                    if ($scope.myItem[i].type == "客户属性") {
                        $scope.g_clientType.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "进件文件") {
                        $scope.g_document.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "上牌人情况") {
                        $scope.g_condition.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "预审结果") {
                        $scope.g_preResult.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "终审结果") {
                        $scope.g_finallyResult.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "期数") {
                        $scope.g_periods.push($scope.myItem[i]);
                    }
                }
                $scope.detail();
            });
        }
        $scope.getMyItem();
        $scope.detail = function() {
            appService.detail($scope.id).then(function(data) {
                $scope.customer = data.content;
                $scope.getItemDetail = function(data, key, obj) {
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if (obj[key] == data[i].value) {
                                obj[key] = data[i].keyword;
                                break;
                            }
                        }
                    }

                }
                $scope.getItemDetail($scope.g_clientType, "clientProperty", $scope.customer);
                $scope.getItemDetail($scope.g_document, "intoWay", $scope.customer);
                $scope.getItemDetail($scope.g_condition, "situation", $scope.customer);
                $scope.getItemDetail($scope.g_preResult, "prequalification", $scope.customer);
                $scope.getItemDetail($scope.g_finallyResult, "the", $scope.customer);
                $scope.getItemDetail($scope.g_periods, "periods", $scope.customer);
                $scope.getItemDetail($scope.g_periods, "surchargePeriods", $scope.customer);
            });
        }
        $scope.update = function() {
            $state.go("customerAdd", { id: $scope.id });
        }
    }
]);
mainApp.controller('customerAddCtrl', ["$scope", "DPUtil", "$stateParams", "$state", "$ionicPopup", "appService", "customerService", "brandManageService", "carManageService", "storeManageService", "salesmanManageService", "itemService",
    function($scope, DPUtil, $stateParams, $state, $ionicPopup, appService, customerService, brandManageService, carManageService, storeManageService, salesmanManageService, itemService) {
        $scope.id = $stateParams.id;
        $scope.g_clientType = [];
        $scope.g_document = [];
        $scope.g_condition = [];
        $scope.g_preResult = [];
        $scope.g_finallyResult = [];
        $scope.g_periods = [];
        $scope.myItem = [];
        $scope.customer = {};
        $scope.title = "添加";
        $scope.brands = [];
        $scope.cars = [];
        $scope.stores = [];
        $scope.sells = [];
        $scope.customer.request_date = new Date();
        // 获取大小项目
        $scope.getMyItem = function() {
            if ($scope.myItem.length > 0) {
                return false;
            }
            appService.item({
                page: 1,
                rows: 9000
            }).then(function(data) {
                $scope.myItem = data.content;
                for (var i = 0; i < $scope.myItem.length; i++) {
                    if ($scope.myItem[i].type == "客户属性") {
                        $scope.g_clientType.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "进件文件") {
                        $scope.g_document.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "上牌人情况") {
                        $scope.g_condition.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "预审结果") {
                        $scope.g_preResult.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "终审结果") {
                        $scope.g_finallyResult.push($scope.myItem[i]);
                    } else if ($scope.myItem[i].type == "期数") {
                        $scope.g_periods.push($scope.myItem[i]);
                    }
                }
            });
        }
        $scope.getMyItem();
        $scope.getBrand = function() {
            brandManageService.allList().then(function(data) {
                $scope.brands = data;
            });
        }
        $scope.getBrand();
        $scope.getStore = function() {
            var param = $scope.customer.brandId;
            if (param) {
                storeManageService.allList(param).then(function(data) {
                    $scope.customer.companyId = "";
                    $scope.stores = data;
                    $scope.customer.carId = "";
                    $scope.cars = [];
                    $scope.customer.sellId = "";
                    $scope.sells = [];
                    $scope.clientSelect = [];
                    $scope.customer.clientRate = '', $scope.customer.dealerRate = '', $scope.customer.venderRate = '';
                });
            }

        }
        $scope.getCar = function() {
            var id = $scope.customer.companyId;
            if (id) {
                carManageService.getListByCompany(id).then(function(data) {
                    $scope.customer.carId = "";
                    $scope.cars = data;
                    $scope.clientSelect = [];
                    $scope.customer.clientRate = '', $scope.customer.dealerRate = '', $scope.customer.venderRate = '';
                });
            }

            var obj_sale = {
                companyId: $scope.customer.companyId,
                page: 1,
                rows: 999999
            }
            if (obj_sale.companyId) {
                salesmanManageService.list(obj_sale).then(function(data) {
                    $scope.customer.sellId = "";
                    $scope.sells = data.content;
                });
            }

        }
        $scope.clientSelect = [], $scope.dealerSelect = [], $scope.venderSelect = [];
        $scope.choosePeriod = function() {
            var carId = $scope.customer.carId;
            if (!carId || !$scope.customer.periods) {
                return false;
            }
            $scope.clientSelect = [], $scope.dealerSelect = [], $scope.venderSelect = [];
            $scope.customer.clientRate = '', $scope.customer.dealerRate = '', $scope.customer.venderRate = '';
            carManageService.getListByCarAndPeriods(carId, $scope.customer.periods).then(function(data) {
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        $scope.clientSelect.push(data[i].clientRate);
                        $scope.dealerSelect.push(data[i].dealerRate);
                        $scope.venderSelect.push(data[i].venderRate);
                    }
                }
            });
        }
        $scope.chooseClientFee = function() {
            for (var i = 0; i < $scope.clientSelect.length; i++) {
                if ($scope.clientSelect[i] == $scope.customer.clientRate) {
                    $scope.customer.dealerRate = $scope.dealerSelect[i];
                    $scope.customer.venderRate = $scope.venderSelect[i];
                    break;
                }
            }

        }
        // 修改时获得数据
        if ($scope.id) {
            $scope.title = "修改";
            $scope.UpdateItemData = function(stores, cars, sells, clientSelect) {
                $scope.stores = stores;
                $scope.cars = cars;
                $scope.sells = sells;
                $scope.clientSelect = clientSelect;
            };
            $scope.getUpdateItem = function(key) {
                $scope.getMyItem();
                var stores = [],
                    cars = [],
                    sells = [],
                    clientSelect = [];
                if (!key.brandId) {
                    $scope.UpdateItemData(stores, cars, sells, clientSelect);
                    return false;
                }
                storeManageService.allList(key.brandId).then(function(data) {
                    stores = data;
                    if (!key.companyId) {
                        $scope.UpdateItemData(stores, cars, sells, clientSelect);
                        return false;
                    }
                    carManageService.getListByCompany(key.companyId).then(function(data) {
                        cars = data;
                        var obj_sale = {
                            companyId: key.companyId,
                            page: 1,
                            rows: 999999,
                        }
                        salesmanManageService.list(obj_sale).then(function(data) {
                            sells = data.content;
                            if (!key.carId || !key.periods) {
                                $scope.UpdateItemData(stores, cars, sells, clientSelect);
                                return false;
                            }
                            carManageService.getListByCarAndPeriods(key.carId, key.periods).then(function(data) {
                                if (data.length > 0) {
                                    for (var i = 0; i < data.length; i++) {
                                        clientSelect.push(data[i].clientRate);
                                    }
                                }
                                $scope.UpdateItemData(stores, cars, sells, clientSelect);
                            });

                        });

                    });

                });
            };
            $scope.detail = function() {
                appService.detail($scope.id).then(function(data) {
                    $scope.customer = data.content;
                    $scope.customer.request_date = new Date($scope.customer.requestDate);
                    $scope.customer.into_date = new Date($scope.customer.intoDate);
                    $scope.customer.loan_date = new Date($scope.customer.loanDate);
                    $scope.customer.credit_date = new Date($scope.customer.creditDate);
                    $scope.customer.situation = Number($scope.customer.situation);
                    $scope.customer.isPledge = "" +$scope.customer.isPledge;
                    $scope.getUpdateItem($scope.customer);
                });
            }
            $scope.detail();
        }
        $scope.sure = function() {
            if ($scope.customer.phone&&$scope.customer.phone.length!=11) {
                $ionicPopup.alert({
                    title: "提示",
                    template: "请输入正确的手机号码",
                    okText: "确定"
                });
                return false;
            }
            if ($scope.customer.idcard&&!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test($scope.customer.idcard))) {
                $ionicPopup.alert({
                    title: "提示",
                    template: "请输入正确的身份证号码",
                    okText: "确定"
                });
                return false;
            }
            $scope.customer.request_date_param = DPUtil.getDateToString($scope.customer.request_date);
            $scope.customer.into_date_param = DPUtil.getDateToString($scope.customer.into_date);
            $scope.customer.loan_date_param = DPUtil.getDateToString($scope.customer.loan_date);
            $scope.customer.credit_date_param = DPUtil.getDateToString($scope.customer.credit_date);
            if (!$scope.id) {
                appService.add($scope.customer).then(function(data) {
                    if (data.success) {
                        $state.go("customerList");
                    } else {
                        $ionicPopup.alert({
                            title: "提示",
                            template: data.failureMessage,
                            okText: "确定"
                        });
                    }
                });
            } else {
                appService.update($scope.customer).then(function(data) {
                    if (data.success) {
                        $state.go("customerDetail", { id:$scope.id });
                    } else {
                        $ionicPopup.alert({
                            title: "提示",
                            template: data.failureMessage,
                            okText: "确定"
                        });
                    }
                });
            }

        }
        $scope.back = function(){
            if ($scope.id) {
                $state.go("customerDetail", { id:$scope.id });
            }else{
                $state.go("customerList");
            }
        }
    }
]);